package com.mobiporter.adias.tags;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.mobiporter.adias.constants.RequestScopeObjects;
import com.mobiporter.adias.tags.model.SelectItem;

public abstract class MobiTag extends TagSupport 
{
	private static final long serialVersionUID = 2888453494221143696L;
	private static Log log = LogFactory.getLog(TagSupport.class);
	private String id ;
	
	public MobiTag()
	{
		super();
	}
	
	public void setId(String id) 
	{
		this.id = id;
	}
	
	public String getId() {
		return id;
	}

	public void writeOut(String html)
	{
		try 
		{
			pageContext.getOut().write(html);
		} 
		catch (IOException e) 
		{
			log.error("Error writing html out :"+e.getMessage());
		}
	}
	

	public void setValue()
	{
		String id = getId() ;
		HashMap<String, String> parameterMap = getParameterMap() ;
		if (parameterMap==null)
		{
			setValueToControl(null);
			return ;
		}
		else
		{
			if (parameterMap.containsKey(id))
			{
				setValueToControl(parameterMap.get(id)) ;
			}
			else
			{
				setValueToControl(null);
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	public HashMap<String, List<SelectItem>> getSelectItemsList()
	{
		HashMap<String, List<SelectItem>> items =  (HashMap<String, List<SelectItem>>) pageContext.getSession().getAttribute(RequestScopeObjects.SELECT_BOX_VALUES);
		if (items == null)
		{
			items = new HashMap<String, List<SelectItem>>() ;
			pageContext.getSession().setAttribute(RequestScopeObjects.SELECT_BOX_VALUES, items );
		}
		return items ;
	}
	
	public  abstract void setValueToControl(String value) ;
	
	/**
	 * This method gets the parameter Map
	 */
	@SuppressWarnings("unchecked")
	public HashMap<String, String> getParameterMap()
	{
		return (HashMap<String, String>) pageContext.getAttribute(RequestScopeObjects.PARAMETER_MAP); 
	}
	
	public String getUserAgent()
	{
		return ((HttpServletRequest)pageContext.getRequest()).getHeader("user-agent");
	}
	
	
}
